<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" class="search-form">
<!--      <el-form-item label="商家id" prop="businessId">-->
<!--        <el-input-->
<!--          v-model="queryParams.bussinessId"-->
<!--          placeholder="请输入商家id"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="店铺开门时间" prop="shopOpenTime" label-width="120px">
        <el-date-picker clearable
          v-model="queryParams.shopOpenTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择店铺开门时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="店铺是否营业" prop="shopStatus" label-width="150px">
        <el-select v-model="queryParams.shopStatus" clearable placeholder="请选择店铺状态" style="width: 200px">
          <el-option v-for="opt in SHOP_STATUS_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="店铺关门时间" prop="shopCloseTime" label-width="150px">
        <el-date-picker clearable
          v-model="queryParams.shopCloseTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择店铺关门时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入店铺名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['order:shop:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:shop:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:shop:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['order:shop:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="门店头像" align="center" prop="shopAvatar" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.shopAvatar" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="center" prop="shopName" />
<!--      <el-table-column label="店铺id，主键自增" align="center" prop="shopId" />-->
      <el-table-column label="联系人姓名" align="center" prop="businessName" />
      <el-table-column label="店铺联系电话" align="center" prop="shopTel" />
      <el-table-column label="详细地址" align="center" prop="shopAddress" />
      <el-table-column label="门牌号" align="center" prop="roomNo" />
      <el-table-column label="店铺是否营业" align="center" width="90px">
        <!-- 使用默认插槽自定义渲染内容 -->
        <template #default="scope">
          <span v-html="formatShopStatus(scope.row.shopStatus)"></span>
        </template>
      </el-table-column>
      <el-table-column label="店铺开始营业时间" align="center" prop="shopOpenTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.shopOpenTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺结束营业时间" align="center" prop="shopCloseTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.shopCloseTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺公告" align="center" prop="shopAnnouncement" />
      <el-table-column label="门店简介" align="center" prop="shopIntroduce" />
      <el-table-column label="店铺的商业类型" align="center" prop="shopType" />
      <el-table-column label="店铺照片" align="center" prop="shopPhoto" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.shopPhoto" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="营业执照" align="center" prop="shopLicense" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.shopLicense" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="店铺余额" align="center" prop="shopProfit" />
      <el-table-column label="配送费" align="center" prop="deliveryFee" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['order:shop:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['order:shop:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改已入驻商家对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="shopRef" :model="form" :rules="rules" >
        <el-form-item label="商家ID" prop="businessId">
          <el-input v-model="form.businessId" placeholder="请输入商家ID" />
        </el-form-item>
        <el-form-item label="联系人姓名" prop="businessName" >
          <el-input v-model="form.businessName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="店铺开门时间" prop="shopOpenTime">
          <el-date-picker clearable
            v-model="form.shopOpenTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择店铺开门时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="店铺关门时间" prop="shopCloseTime">
          <el-date-picker clearable
            v-model="form.shopCloseTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择店铺关门时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="店铺状态" prop="shopStatus">
          <el-select v-model="form.shopStatus" placeholder="请选择店铺状态" style="width: 240px">
            <el-option v-for="opt in SHOP_STATUS_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="店铺公告" prop="shopAnnouncement">
          <el-input v-model="form.shopAnnouncement" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="form.shopName" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="店铺联系电话" prop="shopTel">
          <el-input v-model="form.shopTel" placeholder="请输入店铺联系电话" />
        </el-form-item>
        <el-form-item label="门店地址" prop="shopAddress">
          <el-input v-model="form.shopAddress" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="门店简介" prop="shopIntroduce">
          <el-input v-model="form.shopIntroduce" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="门店头像" prop="shopAvatar">
          <image-upload v-model="form.shopAvatar"/>
        </el-form-item>
        <el-form-item label="店铺照片" prop="shopPhoto">
          <image-upload v-model="form.shopPhoto"/>
        </el-form-item>
        <el-form-item label="营业执照" prop="shopLicense">
          <image-upload v-model="form.shopLicense"/>
        </el-form-item>
<!--        <el-form-item label="店铺余额" prop="shopProfit">-->
<!--          <el-input v-model="form.shopProfit" placeholder="请输入店铺余额" />-->
<!--        </el-form-item>-->
        <el-form-item label="配送费" prop="deliveryFee">
          <el-input v-model="form.deliveryFee" placeholder="请输入配送费" />
        </el-form-item>
        <el-form-item label="门牌号" prop="roomNo">
          <el-input v-model="form.roomNo" placeholder="请输入门牌号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Shop">
import { listShop, getShop, delShop, addShop, updateShop} from "@/api/order/shop"
import {getBusiness} from "@/api/order/business"


const { proxy } = getCurrentInstance()

const shopList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    businessId: null,
    businessName: null,
    shopStatus: null,
    shopOpenTime: null,
    shopCloseTime: null,
    shopAnnouncement: null,
    shopName: null,
    shopTel: null,
    shopAddress: null,
    shopIntroduce: null,
    shopType: null,
    shopAvatar: null,
    shopPhoto: null,
    shopLicense: null,
    shopProfit: null,
    deliveryFee: null,
    roomNo: null
  },
  rules: {
    businessId: [
      { required: true, message: "商家ID不能为空", trigger: "blur" }
    ],
    businessName: [
      { required: true, message: "联系人姓名不能为空", trigger: "blur" }
    ],
    shopStatus: [
      { required: true, message: "店铺状态不能为空", trigger: "change" }
    ],
    shopOpenTime: [
      { required: true, message: "店铺开门时间不能为空", trigger: "blur" }
    ],
    shopCloseTime: [
      { required: true, message: "店铺关门时间不能为空", trigger: "blur" }
    ],
    shopName: [
      { required: true, message: "店铺名称不能为空", trigger: "blur" }
    ],
    shopTel: [
      { required: true, message: "店铺联系电话不能为空", trigger: "blur" }
    ],
    shopAddress: [
      { required: true, message: "门店地址不能为空", trigger: "blur" }
    ],
    shopType: [
      { required: true, message: "店铺的商业类型不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
/** 查询已入驻商家列表 */
async function getList() {
  loading.value = true
  try {
    let rows = []
    // 若选择了状态，按该状态查询；否则按原逻辑合并 1 和 2
    if (queryParams.value.shopStatus) {
      const res = await listShop({ ...queryParams.value })
      rows = res.rows || []
      total.value = res.total || rows.length
    } else {
      const [res1, res2] = await Promise.all([
        listShop({ ...queryParams.value, shopStatus: 1 }),
        listShop({ ...queryParams.value, shopStatus: 2 })
      ])
      rows = [...(res1.rows || []), ...(res2.rows || [])]
          .filter((item, idx, self) => self.findIndex(i => i.shopId === item.shopId) === idx)
      total.value = rows.length
    }

    // 补充联系人姓名
    const settled = await Promise.all(rows.map(async shop => {
      try {
        const businessInfo = await getBusiness(shop.businessId)
        return { ...shop, businessName: businessInfo.data?.businessName || '未知联系人' }
      } catch {
        return { ...shop, businessName: '获取失败' }
      }
    }))

    shopList.value = settled
  } catch (e) {
    console.error('查询店铺列表失败:', e)
  } finally {
    loading.value = false
  }
}
const SHOP_STATUS_OPTIONS = [
  { value: 1, label: '正常营业' },
  { value: 2, label: '暂停营业' },
  { value: 3, label: '审核中' },
  { value: 4, label: '审核不通过' }
]
const formatShopStatus = (status) => {
  // 状态映射配置：文字、文字颜色、背景色
  const statusMap = {
    1: {
      text: '正常营业',
      textColor: '#10b981', // 亮绿色
      bgColor: '#dcfce7'    // 浅绿色背景
    },
    2: {
      text: '暂停营业',
      textColor: '#ef4444', // 亮红色
      bgColor: '#fee2e2'    // 浅红色背景
    },
    3: {
      text: '审核中',
      textColor: '#f59e0b', // 琥珀色
      bgColor: '#fef3c7'    // 浅琥珀色背景
    }
  };

  // 获取当前状态配置（默认未知状态）
  const config = statusMap[status] || {
    text: `未知状态(${status})`,
    textColor: '#6b7280',  // 中性灰
    bgColor: '#f3f4f6'     // 浅灰色背景
  };

  // 返回带样式的 HTML 字符串
  return `<span style="
    color: ${config.textColor};
    background-color: ${config.bgColor};
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
  ">${config.text}</span>`;
};

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    shopId: null,
    businessName: null,
    shopStatus: null,
    shopOpenTime: null,
    shopCloseTime: null,
    shopAnnouncement: null,
    shopName: null,
    shopTel: null,
    shopAddress: null,
    shopIntroduce: null,
    shopType: null,
    shopAvatar: null,
    shopPhoto: null,
    shopLicense: null,
    shopProfit: null,
    deliveryFee: null,
    roomNo: null
  }
  proxy.resetForm("shopRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.shopId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加已入驻商家"
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  // const _shopId = row.shopId || ids.value
  const shopDetail = await getShop(row.shopId);
  const businessName = row.businessName || '未知联系人';
  form.value = {
    ...shopDetail.data, // 店铺基本信息
    businessName: businessName // 关键：同步联系人姓名到表单
  };
  open.value = true;
  title.value = "修改已入驻商家"
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["shopRef"].validate(valid => {
    if (valid) {
      if (form.value.shopId != null) {
        updateShop(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addShop(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _shopIds = row.shopId || ids.value
  proxy.$modal.confirm('是否确认删除已入驻商家编号为"' + _shopIds + '"的数据项？').then(function() {
    return delShop(_shopIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('order/shop/export', {
    ...queryParams.value
  }, `shop_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<!--<style scoped>-->
<!--/* 核心：取消默认浮动，强制 label 和输入框同行 */-->
<!--.search-form .el-form-item {-->
<!--  /* 取消表单项的默认块级布局 */-->
<!--  display: inline-flex;-->
<!--  align-items: center; /* 垂直居中对齐 */-->
<!--  margin-right: 20px; /* 表单项之间的间距 */-->
<!--  margin-bottom: 10px; /* 上下间距（防止换行时重叠） */-->
<!--}-->

<!--/* 确保 label 不换行且与输入框同行 */-->
<!--.search-form .el-form-item__label {-->
<!--  float: none; /* 取消 Element 默认的浮动 */-->
<!--  display: inline-block;-->
<!--  white-space: nowrap; /* 禁止 label 文本换行 */-->
<!--  margin-right: 10px; /* label 与输入框的间距 */-->
<!--}-->

<!--/* 输入框容器样式调整 */-->
<!--.search-form .el-form-item__content {-->
<!--  float: none; /* 取消默认浮动 */-->
<!--  display: inline-block;-->
<!--  width: auto; /* 自适应内容宽度 */-->
<!--}-->

<!--/* 调整输入框和日期选择器的宽度（可选） */-->
<!--.search-form .el-input,-->
<!--.search-form .el-date-picker {-->
<!--  width: 200px; /* 固定宽度，保持整齐 */-->
<!--}-->

<!--/* 按钮组样式调整 */-->
<!--.search-form .el-form-item:last-child {-->
<!--  margin-left: 10px; /* 与前面表单项的间距 */-->
<!--}-->
<!--</style>-->